package com.globalwave.common.tree
{
	import com.globalwave.common.event.RecordEvent;
	import com.globalwave.util.HttpServiceUtil;
	import com.globalwave.util.TreeUtil;
	import com.globalwave.util.XmlUtil;
	
	import flash.display.DisplayObject;
	import flash.events.ContextMenuEvent;
	import flash.events.MouseEvent;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	
	import mx.collections.ArrayCollection;
	import mx.collections.XMLListCollection;
	import mx.containers.TitleWindow;
	import mx.controls.Alert;
	import mx.controls.Tree;
	import mx.core.FlexGlobals;
	import mx.events.CloseEvent;
	import mx.events.FlexEvent;
	import mx.events.ListEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class Tree4List extends Tree
	{
		public var rootDisplayName : String ;
		public var idFieldName : String = "catalog_id";
		public var proIdFieldName : String = "pro_catalog_id" ;
		public var stateFieldName : String ;
		public var listUrl : String = null ;
		public var deleteUrl : String = null ;
		public var editWindowClass : Class = null ;
		[Bindabled]
		public var treeData : XML ;
		
		public function Tree4List() {
            super();
			this.labelField = "@name_" ;
			this.showRoot=true ;
			this.percentWidth=100 ;
			this.percentHeight=100 ;
			this.dragEnabled=true ;
			this.dropEnabled=true ;
			this.dragMoveEnabled=true ;
			this.addEventListener(FlexEvent.INITIALIZE, catalogListFE) ;
			//this.addEventListener(flash.events.MouseEvent.CLICK, ee) ;
			//this.addEventListener(ListEvent.ITEM_CLICK, getSubItemObject) ;
			
			this.contextMenu = new ContextMenu() ;
			this.contextMenu.hideBuiltInItems() ;
			
			var menuItem : ContextMenuItem = new ContextMenuItem("Add Child", false, true, true);
			menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, catalogAddChildCME);
			this.contextMenu.customItems.push(menuItem);	
			
			menuItem = new ContextMenuItem("Add Sibling", false, true, true);
			menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, catalogAddSiblingCME);
			this.contextMenu.customItems.push(menuItem);	
			
			menuItem = new ContextMenuItem("Update", false, true, true);
			menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, catalogUpdateCME);
			this.contextMenu.customItems.push(menuItem);	
			
			menuItem = new ContextMenuItem("_Delete", false, true, true);
			menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, catalogDeleteCME);
			this.contextMenu.customItems.push(menuItem);	
			
			menuItem = new ContextMenuItem("Refresh", false, true, true);
			menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, catalogListCME);
			this.contextMenu.customItems.push(menuItem);

        }
		
		private function catalogListFE(event : FlexEvent):void {
			catalogList() ;
		}	
		private function catalogListCME(event : ContextMenuEvent):void {
			catalogList() ;
		}	
		public function catalogAddSiblingCME(event : ContextMenuEvent):void {
			catalogAdd(false) ;
		}
		public function catalogAddChildCME(event : ContextMenuEvent):void {
			catalogAdd(true) ;
			/*
			if (this.selectedItem == null) {
				Alert.show( "请选择一条记录！" );
				return ;
			}
			
			var app : DisplayObject = DisplayObject(FlexGlobals.topLevelApplication) ;
			var editWindow : TreeEditWindow = 
				TreeEditWindow(PopUpManager.createPopUp(app, editWindowClass, true));
			
			editWindow.parentObject = this.selectedItem ;
			
			editWindow.addEventListener(RecordEvent.ADD_SUCCESS, addItem);
			*/
		}
		public function catalogUpdateCME(event : ContextMenuEvent):void {
			catalogUpdate() ;
		}
		public function catalogDeleteCME(event : ContextMenuEvent):void {
			catalogDelete() ;
		}
		
		private function catalogAdd(isAddChild : Boolean):void {
			
			if (this.selectedItem == null) {
				Alert.show( "请选择一条记录！" );
				return ;
			}
			
			if (!isAddChild && (this.selectedItem as XML).parent() == null) {
				Alert.show( "根目录，不能加入同级目录！" );
				return ;
			}
			
			var app : DisplayObject = DisplayObject(FlexGlobals.topLevelApplication) ;
			var editWindow : TreeEditWindow = 
				TreeEditWindow(PopUpManager.createPopUp(app, editWindowClass, true));
			
			if (isAddChild) {
				editWindow.parentObject = this.selectedItem ;
			} else {
			    editWindow.parentObject = (this.selectedItem as XML).parent() ;
			}
			
			editWindow.addEventListener(RecordEvent.ADD_SUCCESS, addItem);
			
		}
		
		private function catalogUpdate():void {
			
			if (this.selectedItem == null) {
				Alert.show( "请选择一条记录！" );
				return ;
			}
			
			if ((this.selectedItem as XML).parent() == null) {
				Alert.show( "根目录，不能更新！" );
				return ;
			}
			
			var app : DisplayObject = DisplayObject(FlexGlobals.topLevelApplication) ;
			var editWindow : TreeEditWindow = 
				TreeEditWindow(PopUpManager.createPopUp(app, editWindowClass, true));
			
			editWindow.updateObject = this.selectedItem ;
			editWindow.parentObject = (this.selectedItem as XML).parent() ;
			
			editWindow.addEventListener(RecordEvent.UPDATE_SUCCESS, updateItem) ;
		}
		
		private function catalogList():void {
			var params :Object = new Object();
			params["sdfasdfasfas"] = "x" ;
			
			var httpService : HTTPService = HttpServiceUtil.getService(listUrl);
			httpService.addEventListener(ResultEvent.RESULT, catalogListOnReturn) ;
			
			httpService.send(params);            
		}

		private function catalogListOnReturn(event:ResultEvent):void {
			
			treeData = buildTree(new XML(event.result)) ;
			dataProvider = treeData ;
			//this.expandItem(this.dataProvider.getItemAt(0), true) ;
			
		}
		
//		private function ee(event : flash.events.MouseEvent):void {
//			this.expandItem(this.dataProvider, true) ;
//		}
		
		public function buildTree(listDataProvider : Object ) : XML {
		
		    var list : XMLList = new XML(listDataProvider).datas ;

		    var tree : XML = <root></root>;
			var rootId : String = "" ;
			
			if (rootDisplayName != null) {
		        tree[this.labelField] = rootDisplayName ;
			}
			
			var isFirstItem : Boolean = true ;
		    var items : XML = <root></root> ;
			
		    for each (var elem :XML in list.children()) {
		    	
		    	var item : XML = <item></item> ;
		    	
		    	if (elem[stateFieldName].toString() != "") {
		    		item.@state = "checked"
		    	} else {
		    		item.@state = "unchecked"
		    	}
		    	
		    	item.@isBranch = "false" ;
				
				trace(elem.toXMLString());
		    	
		    	for each (var attrElem : XML in elem.children()) {
		    		item.@[attrElem.name().toString()] = attrElem.valueOf().toString() ;
		    	}
		    
				if (isFirstItem) {// set root
					isFirstItem = false ;
					
					if(rootDisplayName == null) {
						tree = item ;
						rootId = item.@[idFieldName] + ""
					    continue ;
					}
				} 
		        items.appendChild(item) ;
		    }
		    
			
		    for (var i : int = items.children().length() - 1 ; i >=0 ; i -- ) {
		        var pro : String = items.item[i].@[proIdFieldName] ;
		        
		        if (pro == rootId) {
					tree.@isBranch = "true" ;
		            tree.prependChild(items.item[i]) ;            
		        } else {
		        	items.item.(@[idFieldName] == pro ).@isBranch = "true" ;
		            items.item.(@[idFieldName] == pro ).prependChild(items.item[i]) ;
		        }
		    }
		        		
		    return tree ;    
						    
		}
		
		public function getSelectedIds() : ArrayCollection {
		    var ids : ArrayCollection = new ArrayCollection() ;
		    var xml : XML = new XML(this.dataProvider) ;
         	getNodeSelectedIds(xml, ids) ;
         	
         	return ids ;
		}
		
		private function getNodeSelectedIds(xml : XML , ids : ArrayCollection) :void {
        	for (var i : int = 0 ; xml != null && i < xml.children().length() ; i ++) {
        		if (xml.children()[i].@state.toString() == "checked") {
        		    ids.addItem(xml.children()[i].@[this.idFieldName].toString()) ;
        		}
        		getNodeSelectedIds(xml.children()[i], ids) ;
        	}
		}
		
		private function addItem(event: RecordEvent) : void {
			var item : XML = TreeUtil.toNode(event.record,"catalog_id");
			var proId : String = item.@pro_catalog_id + "" ;
			if (proId != "") {
				//var treeNode : XMLList = (this.dataProvider[0] as XML).descendants().item.(@catalog_id == proId);
				var treeNode : XML = XmlUtil.findById(treeData, "@catalog_id", proId) ;
				
				if (treeNode == null) {
					treeData.appendChild(item) ;
					treeData.@isBranch = "true" ;
				} else {
					treeNode.appendChild(item) ;
					treeNode.@isBranch = "true" ;
				}
			} else {
				treeData.appendChild(item) ;
			}
			
			
			//dataProvider = treeData ;
			//dataProvider=new HierarchicalData(treeData) ;
		}
		
		private function updateItem(event: RecordEvent) : void {
			var item : XML = TreeUtil.toNode(event.record,"catalog_id");
			var id : String = item.@catalog_id + "" ;
			if (id != "") {
				//var treeNode : XMLList = (this.dataProvider[0] as XML).descendants().item.(@catalog_id == proId);
				//var treeNode : XML = XmlUtil.findById(treeData, "@catalog_id", id) ;
				var treeNode : XML = (this.selectedItem as XML) ;
				
				if (treeNode != null) {
					XmlUtil.copyAttributes(treeNode, item) ;
				}
			} 
			
			
			//dataProvider = treeData ;
			//dataProvider=new HierarchicalData(treeData) ;
		}
		
		
		private function catalogDelete():void {
			if (this.selectedItem == null) {
				Alert.show( "请选择一条记录！" );
				return ;
			}
			
			if (this.selectedItem.children().length() != 0) {
				Alert.show( "必先删除所有子记录！" );
				return ;
			}
			
			if ((this.selectedItem as XML).parent() == null) {
				Alert.show( "根目录，不能删除！" );
				return ;
			}
			
			var msg : String ;
			msg = "是否删除[" + this.selectedItem.@name_ + "]？" ;
			Alert.show( msg , "删除确认", Alert.YES|Alert.NO, this, catalogDeleteOnComfirm);                
		}
		
		private function catalogDeleteOnComfirm(event:CloseEvent):void {
			if (event.detail==Alert.YES) {
				var params :Object = new Object();
				
				params["012345678"] = "012345678" ;
				params["ids"] = this.selectedItem.@catalog_id ;  
				
				
				var httpService : HTTPService = HttpServiceUtil.getService(deleteUrl);
				httpService.addEventListener(ResultEvent.RESULT, catalogDeleteOnReturn) ;
				
				httpService.send(params);     
				
			}            
		}        
		
		public function catalogDeleteOnReturn(event:ResultEvent) : void {
			for (var i : int = this.selectedItems.length - 1 ; i >=0  ; i -- ) {
				var selectedData : XML = (this.selectedItems[i] as XML);
				var id : String = selectedData.@catalog_id ;
				
				//var selectedData : XML = XmlUtil.findById(treeData, "@catalog_id", id) ;
				
				if (selectedData.parent().children().length() == 1 ) {
					selectedData.parent().@isBranch = "false" ;
				}
				
				XmlUtil.deleteElemet(treeData, "@catalog_id", id) ;
				//delete this.selectedItems[i] ;
			}
		}
		
	}
}